//
//  ContactViewController.m
//  Contacts
//
//  Created by 李 雷川 on 14-7-16.
//  Copyright (c) 2014年 李 雷川. All rights reserved.
//

#import "ContactViewController.h"
#import "Contact.h"
#import "ContactCell.h"
#import "ContactDetailViewController.h"
#import  "ServerInterface.h"
#import "Department.h"
#import "TBActivityView.h"
#import "IndicativeView.h"
#import "FileInterface.h"
#import "DepartmentsViewController.h"
#import "ContactTabelViewController.h"
extern Contact *globalContact;
@interface ContactViewController (){
    IndicativeView *indicativeView;
    
}
@property (weak, nonatomic) IBOutlet UITableView *contactTableView;
@end

@implementation ContactViewController
@synthesize contactTableView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"通讯录";
    
    mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    mySearchBar.delegate = self;
    mySearchBar.barStyle = UIBarStyleDefault;
    [mySearchBar setPlaceholder:@"用户名、座机、手机、部门"];
    
    searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:mySearchBar contentsController:self];
    searchDisplayController.active = NO;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    searchDisplayController.delegate =self;
    
    
    self.contactTableView.dataSource = self;
    self.contactTableView.delegate = self;
	self.contactTableView.tableHeaderView = mySearchBar;
    //self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    
    
    [self initContactsData];
    NSDictionary *lastUpdateTimeDic = [FileInterface getLastUpdateTime];
    NSString *updateTime = [lastUpdateTimeDic objectForKey:k_Contact];
    
    NSDictionary *dic = nil;
    updateTime == nil?(dic = @{ @"company_id":CompanyID,@"token":globalContact.token,@"user_id":@(globalContact.userID)}):(dic = @{ @"company_id":CompanyID,@"token":globalContact.token,@"user_id":@(globalContact.userID),k_Contact:updateTime});
    if (!departments) {
        indicativeView = [[IndicativeView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:indicativeView];
        [indicativeView showFriendlyLoadingViewWithText:@"正在加载..." loadingAnimated:YES];
    }
    [ServerInterface getContactsWithContactDis:dic WithBlock:^(NSDictionary *contatsDic, NSError *error) {
        if (error) {
            NSLog(@"error is:%@",error);
        }
        else {
            if ([[contatsDic valueForKeyPath:@"success"] boolValue]) {
                NSMutableDictionary  *updateTimeDic = [NSMutableDictionary dictionaryWithDictionary: [FileInterface getLastUpdateTime]];
                [updateTimeDic setObject:contatsDic[@"currentTime"] forKey:k_Contact];
                [FileInterface saveInterfaceUpdateTime:updateTimeDic];
                NSArray *postsFromResponse = [contatsDic valueForKeyPath:@"data"];
                NSMutableArray *arr = [NSMutableArray arrayWithCapacity:postsFromResponse.count];
                NSInteger newNum = 0;
                NSInteger updateNum =0;
                NSInteger deleteNum = 0;
                for (NSDictionary *attributes in postsFromResponse) {
                    NSArray *contacts = [attributes objectForKey:@"user"];
                    Department *department = [[Department alloc]init];
                    department.ID =  [attributes[@"id"] integerValue];
                    department.name = attributes[@"name"];
                    department.sort = [attributes[@"sort"] integerValue];
                    NSMutableArray *contactArr = [NSMutableArray arrayWithCapacity:[contacts count]];
                    NSInteger isOpertation = [attributes[@"isOperation"] integerValue];
                    switch (isOpertation) {
                        case 0:{
                            newNum ++;
                            [Department saveDepartment:department];
                        }
                            break;
                        case 1:{
                            updateNum  ++;
                            [Department updateDepartment:department];
                        }
                            break;
                        case 2:{
                            [Department deleteDepartment:department];
                            deleteNum  ++;
                        }
                            break;
                        default:
                            break;
                    }
                    for (NSDictionary *userDic in contacts) {
                        Contact *contact = [Contact analysisContactWithDic:userDic];
                        Department *_departemnt = [[Department alloc]init];
                        _departemnt.name =attributes[@"name"];
                        _departemnt.ID = [attributes[@"id"] integerValue];
                        contact.department = _departemnt;
                        NSInteger isOpertation = [attributes[@"isOperation"] integerValue];
                        switch (isOpertation) {
                            case 0:{
                                [Contact saveContact:contact];
                            }
                                break;
                            case 1:{
                                [Contact updateContact:contact];
                            }
                                break;
                            case 2:
                            {
                                [Contact deleteContact:contact];
                            }
                                break;
                                
                            default:
                                break;
                        }
                        [contactArr addObject:contact];
                    }
                    department.contacts = contactArr;
                    [arr addObject:department];
                }
                [self initContactsData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.contactTableView reloadData];
                });
            }
            else{
                NSString *message =[contatsDic objectForKey:@"message"];
                NSLog(@"message is:%@",message);
            }
        }
        if (indicativeView) {
            [indicativeView hideLoadingView];
        }
    }];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)initContactsData{
    departments  =[Department getDepartments];
}

-(void)saveDataToDB{
    [Department saveDepartments:departments];
}

-(void)updateDataToDB{
    [Department updateDepartments:departments];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    NSIndexPath *selected = [contactTableView indexPathForSelectedRow];
    ContactDetailViewController *detailViewController = segue.destinationViewController;
    Contact *contact;
    if (contactTableView == self.searchDisplayController.searchResultsTableView) {
        contact = searchResults[selected.row];
    }
    else {
        Department *department =departments[selected.section -1];
        contact = [department.contacts objectAtIndex:selected.row];
    }
    [detailViewController initWithContact:contact];
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    switch (indexPath.row) {
//        case 0:
//            return
//            break;
//
//        default:
//            break;
//    }
//}

#pragma UITableViewDataSource

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 0;
    }
    else{
        if (section == 0) {
            return 0;
        }
    }
    return 44.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 54.0f;
    }
    return 76.0f;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    }
    else {
        if (section == 0) {
            return nil;
        }
        else{
            Department *department =departments[section - 1];
            return department.name;
        }

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return searchResults.count;
    }
    else {
        if (section == 0) {
            return 2;
        }
        else{
            Department *department =departments[section-1];
            return department.contacts.count;
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 1;
    }
    else {
        return departments.count + 1;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        static NSString *resultCell = @"ResultCell";
        cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:resultCell];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:resultCell];
            [cell.imageView setClipsToBounds:YES];
            [cell.imageView.layer setBorderColor:[UIColor whiteColor].CGColor];
            [cell.imageView.layer setBorderWidth:1.0];
            [cell.imageView.layer setCornerRadius: cell.imageView.frame.size.width/2.0];
        }
        Contact *contact =searchResults[indexPath.row];
        cell.textLabel.text = contact.name;
        cell.detailTextLabel.textColor =[UIColor lightGrayColor];
        cell.detailTextLabel.text =[NSString stringWithFormat:@"座机:%@   手机%@",contact.phone,contact.mobilephone] ;
        
        
        NSString *fullImagePath = [IMAGE_FORDER stringByAppendingPathComponent:contact.headName];
        if ([[NSFileManager defaultManager]fileExistsAtPath:fullImagePath]) {
            cell.imageView.image =[UIImage imageWithContentsOfFile:fullImagePath];
        }
        else{
            [ cell.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:contact.headUrl]]  placeholderImage: [UIImage imageNamed:@"head_small_default.png"]  success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                NSString *filePath =[IMAGE_FORDER stringByAppendingPathComponent:contact.headName];
                BOOL success = [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
                if (success) {
                }
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                
            }];
        }
    }
    else {
        if (indexPath.section == 0) {
            static NSString *departmentCell = @"DepartmentCell";
            cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:departmentCell];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:departmentCell];
            }
            if (indexPath.row == 0) {
                cell.imageView.image = [UIImage imageNamed:@"recently.png"];

                cell.textLabel.text = @"最近联系人";
            }
            else if (indexPath.row ==1){
                cell.imageView.image = [UIImage imageNamed:@"department.png"];
                 cell.textLabel.text = @"部门";
            }
        }
        else{
            static NSString *CellIdentifier = @"ContactCell";
            Department *department = departments[indexPath.section -1];
            NSArray *contacts = department.contacts;

            cell = (ContactCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            ContactCell *contactCell = (ContactCell *)cell;
            [contactCell initWithContact:contacts[indexPath.row]];
        }

    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        ContactDetailViewController *detailViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ContactDetailViewController"];
        [self.navigationController pushViewController:detailViewController animated:YES];
        Contact *contact = searchResults[indexPath.row];
        [detailViewController initWithContact:contact];
    }
    else{
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                ContactTabelViewController *contactTabelViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ContactTabelViewController"];
                [contactTabelViewController initContacts:[Contact lastContacts] withContent:@"最近联系人"];
                [self.navigationController pushViewController:contactTabelViewController animated:YES];
            }
            else if (indexPath.row == 1){
                DepartmentsViewController *departmentsViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"DepartmentsViewController"];
                [self.navigationController pushViewController:departmentsViewController animated:YES];
            }
        }
    }
}

#pragma UISearchDisplayDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"searchBarTextDidBeginEditing");
}
-(void)updateSearchResultWithKey:(NSString *)key{
    searchResults = [Contact searchContactsWithKey:key];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self updateSearchResultWithKey:searchText];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self updateSearchResultWithKey:searchBar.text];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar{
    
}

- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
    NSLog(@"searchDisplayControllerWillBeginSearch");
    
    
    
    
}
- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller{
    NSLog(@"searchDisplayControllerDidBeginSearch");
}
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller{
    NSLog(@"searchDisplayControllerWillEndSearch");
}
- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
    NSLog(@"searchDisplayControllerDidEndSearch");
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    //    [UIView animateWithDuration:0.7 animations:^{
    //        cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    //    } completion:^(BOOL finished) {
    //        ;
    //    }];
}

-(void)enterContactDetail:(Contact*)contact{
    
}

@end
